<template>
	<div class="component-upload-image">
		<el-upload :action="uploadImgUrl" v-bind="uploadConfig" :style="{ opacity: !!imageUrl ? 0 : 1 }">
			<i class="el-icon-plus"></i>
		</el-upload>
		<div class="upload_img" v-if="!!imageUrl">
			<el-image ref="preview" :src="imageUrl" :preview-src-list="previewImage" fit="contain"></el-image>
			<el-button-group>
				<el-button type="text" title="修改" icon="el-icon-edit" @click="handleAmendUpload()"></el-button>
				<el-button type="text" title="预览" icon="el-icon-search" @click="handlePreviewImage()"></el-button>
				<el-button type="text" title="删除" icon="el-icon-delete" @click="handleDeleteImage()"></el-button>
			</el-button-group>
		</div>
	</div>
</template>

<script>
import { getToken } from '@/utils/auth';
import emitter from 'element-ui/src/mixins/emitter';
export default {
	mixins: [emitter],
	props: {
		value: { type: String, default: '' },
		// 大小限制(MB)
		fileSize: { type: Number, default: 5 },
		// 文件类型, 例如['png', 'jpg', 'jpeg']
		fileType: { type: Array, default: () => ['png', 'jpg', 'jpeg'] }
	},
	data() {
		return {
			imageUrl: this.value,
			uploadImgUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 上传的图片服务器地址
			uploadConfig: {
				limit: 1,
				ref: 'upload',
				multiple: false,
				showFileList: false,
				listType: 'picture-card',
				onExceed: this.handleExceed,
				onSuccess: this.handleUploadSuccess,
				beforeUpload: this.handleBeforeUpload,
				accept: this.fileType.map((n) => `.${n}`).join(),
				headers: { Authorization: 'Bearer ' + getToken() }
			}
		};
	},
	watch: {
		value(val) {
			this.imageUrl = val;
		},
		imageUrl(val) {
			this.$emit('input', val);
			this.dispatch('ElFormItem', 'el.form.change', [val]);
		}
	},
	computed: {
		previewImage() {
			return [this.imageUrl];
		}
	},
	methods: {
		// 上传前loading加载
		handleBeforeUpload(file) {
			let isImg = false;
			if (this.fileType.length) {
				let fileExtension = '';
				if (file.name.lastIndexOf('.') > -1) {
					fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
				}
				isImg = this.fileType.some((type) => {
					if (file.type.indexOf(type) > -1) return true;
					if (fileExtension && fileExtension.indexOf(type) > -1) return true;
					return false;
				});
			} else {
				isImg = file.type.indexOf('image') > -1;
			}

			if (!isImg) {
				this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join('/')}图片格式文件!`);
				return false;
			}
			if (this.fileSize) {
				const isLt = file.size / 1024 / 1024 < this.fileSize;
				if (!isLt) {
					this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
					return false;
				}
			}
			this.$modal.loading('正在上传图片，请稍候...');
		},
		// 文件个数超出
		handleExceed() {
			this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
		},
		// 上传成功回调
		handleUploadSuccess(res, file) {
			this.$modal.closeLoading();
			if (res.code === 200) {
				this.imageUrl = res.url;
			}
			this.$refs['upload'].clearFiles();
		},

		//修改上传
		handleAmendUpload() {
			this.$refs['upload'].$refs['upload-inner'].handleClick();
		},

		// 删除图片
		handleDeleteImage() {
			this.imageUrl = '';
		},

		//预览图片
		handlePreviewImage() {
			this.$refs['preview'].clickHandler();
		}
	}
};
</script>
<style lang="scss" scoped>
.component-upload-image::v-deep {
	.el-upload--picture-card {
		width: 198px;
		height: 198px;
		line-height: 206px;
	}
	.upload_img {
		position: absolute;
		top: 0;
		left: 0;
		width: 198px;
		height: 198px;
		border-radius: 4px;
		overflow: hidden;
	}
	.el-image {
		width: 100%;
		height: 100%;
	}
	.el-button-group {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: none;
	}
	.upload_img:hover .el-button-group {
		display: flex;
		align-items: center;
		justify-content: space-around;
		background-color: rgba(0, 0, 0, 0.5);
	}
	.el-button {
		color: #fff;
		font-size: 18px;
	}
}
</style>
